<?php
class Logger {
    private static $log = array();
    
    private static function getTime() {
        $timeArray = explode(' ', microtime());
        return (float)$timeArray[0] + (float)$timeArray[1];
    }
    
    public static function startLog($execName, $contents='') {
        self::log($execName, $contents);
    }
    public static function endLog($execName) {
        self::log($execName);
    }
    
    private static function log($execName,$contents = '') {
        static $sequence = 0;
        if (array_key_exists($execName, self::$log)) {
            if (array_key_exists('endTime', self::$log[$execName])) {
                $lastLog = self::$log[$execName];
                self::$log[$execName] = array($lastLog);
                if ('' != $contents) $logArray['contents'] = $contents;
                $logArray['sequence'] = ++$sequence;
                $logArray['startTime'] = self::getTime();
                self::$log[$execName][] = $logArray;
            } else {
                if (array_key_exists('startTime', self::$log[$execName])) {
                    self::$log[$execName]['endTime'] = self::getTime();
                    self::$log[$execName]['execTime'] = '' . self::$log[$execName]['endTime'] -                                                         self::$log[$execName]['startTime'];
                } else {
                    $logLen = sizeof(self::$log[$execName]);
                    if (array_key_exists('endTime', self::$log[$execName][$logLen - 1])) {
                        if ('' != $contents) $logArray['contents'] = $contents;
                        $logArray['sequence'] = ++$sequence;
                        $logArray['startTime'] = self::getTime();
                        self::$log[$execName][] = $logArray;
                    } else {
                        self::$log[$execName][$logLen-1]['endTime'] = self::getTime();
                        self::$log[$execName][$logLen-1]['execTime'] = '' . self::$log[$execName][$logLen-1]['endTime'] -                                                         self::$log[$execName][$logLen-1]['startTime'];
                    }
                }
            }
        } else {
            if ('' != $contents) $logArray['contents'] = $contents;
            $logArray['sequence'] = ++$sequence;
            $logArray['startTime'] = self::getTime();
            self::$log[$execName] = $logArray;
        }
    }
    
    public static function dumpLog() {
        if (sizeof(self::$log) > 0) {
            echo '<pre>';
            print_r(self::$log);
            echo '</pre>';
        }        
    }

    public static function dumpToFile($file, $contents='') {
        if ('' == $contents) $contents = self::$log;
        if (false ==is_string($contents)) {
            $contents = str_replace("=> \n", '=>', var_export($contents, true));
        }
        file_put_contents($file, $contents);
    }
}
?>